<template>
  <div class="gis-edit-panel-container">
    <!-- loading -->
    <div v-show="spinning" class="loading"><a-spin :spinning="spinning" /></div>
    <div class="left-super-container">
      <!-- 头部 -->
      <div class="gis-data-header">
        <div class="left-header">
          <span>{{ selectLayer ? selectLayer.name : '' }}</span>
          <!--          <span v-if="selectLayer ? !selectLayer.visible: false" class="visible-state">(不可见状态)</span>-->
          <span v-if="columnCount > 0" class="count-info"
            >共有{{ columnCount }}个字段, {{ dataNumberCount }}行</span
          >
          <!-- 历史操作 -->
          <!--          <span class="history-toggle-icon">-->
          <!--             <a-icon-font-->
          <!--               type="iconqingxi-caozuojilu"-->
          <!--               @click="toggleHistoryMode()"-->
          <!--             />-->
          <!--          </span>-->
        </div>
        <!-- 头部右侧按钮 -->
        <div class="right-header">
          <!-- 收起, 综合搜索, 重置, 导出 -->
          <a-tooltip
            v-for="icon in headerIconArray"
            :key="icon.action"
            :mouse-enter-delay="icon.delay"
            placement="top"
          >
            <template slot="title">
              <span>{{ icon.title }}</span>
            </template>
            <span
              class="tool-btn"
              :class="{ 'disabled-btn': icon.disabled }"
              @click="handleClick(icon.action)"
            >
              <a-icon-font :type="icon.icon" />
            </span>
          </a-tooltip>
          <!-- 全屏 -->
          <a-tooltip :mouse-enter-delay="0.5" placement="top">
            <template slot="title">
              <span>{{ fullScreenState ? '退出全屏' : '全屏显示' }}</span>
            </template>
            <span class="tool-btn" @click="fullScreen(false)">
              <a-icon-font
                :type="
                  fullScreenState
                    ? 'icontuichuquanping'
                    : 'iconfangdahuabanquanping'
                "
              />
            </span>
          </a-tooltip>
        </div>
      </div>
      <div class="left-main">
        <!-- 历史操作 -->
        <!-- <history-list-->
        <!--   v-show="isShowHistory"-->
        <!--   :is-show-history="isShowHistory"-->
        <!--   @toggle-history-mode="(value) => (isShowHistory = value)"-->
        <!--   @change-history="onChangeHistory"-->
        <!--/>-->
        <div class="middle-container">
          <!-- 列卡片 -->
          <gis-layer-data-columns
            :is-visitor="isVisitor || isLock"
            class="data-columns"
          />
          <!-- 数据表 -->
          <gis-data-table
            ref="nodeEditPanelTable"
            :is-visitor="isVisitor || isLock"
            class="data-table"
          />
        </div>
      </div>
    </div>
    <layer-export-popup
      :export-layer="selectLayer"
      :project-id="projectId"
      :tab-id="currentTabId"
      :load-visible="exportLayerModalVisible"
      :column-count="columnCount"
      @confirm="confirmLayerExport"
      @cancel="exportLayerModalVisible = false"
    />
  </div>
</template>

<script lang="ts">
import { Vue, Component, Watch, Prop } from 'vue-property-decorator'
import HistoryList from '@/components/studio/data/node-edit-panel/HistoryList.vue'
import GisDataTable from '@/components/gis/layer-detail-data/GisDataTable.vue'
import GisLayerDataColumns from '@/components/gis/layer-detail-data/GisLayerDataColumns.vue'
import LayerExportPopup from '@/components/gis/popup/LayerExportPopup.vue'
import {
  setWatermark,
  deleteWatermark,
  removeResizeListener,
} from '@/util/util'
import UserStore from '@/store/modules/user'
import GisStore from '@/store/modules/gis'
import { debounce } from 'lodash'

// import { baseURL } from '@/api/axios-config'
// @ts-ignore
const elementResizeDetectorMaker = require('element-resize-detector')

@Component({
  components: {
    HistoryList,
    GisDataTable,
    GisLayerDataColumns,
    LayerExportPopup,
  },
})
export default class GisLayerDetailData extends Vue {
  // 当前图层
  public get selectLayer() {
    return GisStore.selectLayer
  }

  @Prop({ type: Number }) currentTabId!: number //  当前 tabId

  public get projectId() {
    return GisStore.projectId
  }

  private headerIconArray: any[] = [
    {
      title: '收起',
      action: 'packUp',
      icon: 'iconicon-beifen',
      delay: 0.5,
      disabled: false,
    },
    {
      title: '综合搜索',
      action: 'comprehensiveSearch',
      icon: 'iconsousuo',
      delay: 0.5,
      disabled: true,
    },
    {
      title: '重置',
      action: 'resetForm',
      icon: 'icona-qingxi-caozuojilubeifen3',
      delay: 0.5,
      disabled: true,
    },
    {
      title: '导出',
      action: 'onExport',
      icon: 'iconxiazaibendi',
      delay: 0.5,
      disabled: false,
    },
  ]

  public exportLayerModalVisible: boolean = false // 导出数据 modal

  // 查询数据的表名取决于当前历史记录的表名，没有的话取 selectLayer 的表名
  private get tableName(): string {
    return GisStore.selectLayer?.viewName
  }

  private isShowHistory: boolean = false // 历史记录显示
  private middleContainer: any
  private spinning: boolean = false // loading
  // 全屏显示
  public get fullScreenState(): boolean {
    return GisStore.fullScreenState
  }

  // 用户名
  public get username() {
    return UserStore.currentUser ? UserStore.currentUser.name : '未命名用户'
  }

  private get isTableDetailLoading() {
    return GisStore.isTableDetailLoading
  }

  @Watch('isTableDetailLoading')
  private onIsTableDetailLoading() {
    this.spinning = this.isTableDetailLoading
  }

  // 访问者
  public get isVisitor() {
    return true
    // return DataViewStore.isVisitor
  }

  // 锁定状态
  public get isLock() {
    return false
    // return DataViewStore.getLock
  }

  // 表列数
  get columnCount() {
    return GisStore.layerTableColumns.length
  }

  // 后台接口变更，现在从output中取 表行数
  get dataNumberCount() {
    return GisStore.tableDataCount
  }

  private get selectedColumns() {
    return GisStore.selectedColumns
  }

  /**
   * mounted
   */
  public mounted() {
    this.onContainerResize()
  }

  /**
   * 数据详情容器大小改变
   * @private
   */
  private onContainerResize() {
    const rootErd = elementResizeDetectorMaker({
      strategy: 'scroll', //  <- For ultra performance.
      callOnAdd: false,
    })
    this.middleContainer = document.querySelector(
      '.middle-container'
    ) as HTMLElement
    rootErd.listenTo(this.middleContainer, (element: HTMLElement) => {
      this.dataDetailResizeDebounce(element)
    })
    this.$once('hook:beforeDestroy', () => {
      deleteWatermark('water_mark')
      removeResizeListener()
      rootErd.removeAllListeners(this.middleContainer)
    })
  }

  public dataDetailResizeDebounce = debounce(
    (element: HTMLElement) => this._dataDetailResize(element),
    500
  )

  /**
   * 详情模块高度修改
   */
  private _dataDetailResize(element: HTMLElement) {
    this.$nextTick(() => {
      // 监听到事件后执行的业务逻辑
      const areaName = '.middle-container'
      setWatermark(this.username, areaName)
    })
    // 列卡片高度 266， 表格 padding-top: 5
    if (element.offsetHeight > 0) {
      GisStore.setTableHeight(element.offsetHeight - 271)
      GisStore.setGisDataWidth(element.offsetWidth)
    }
  }

  /**
   * toggle 历史记录
   */
  public toggleHistoryMode() {
    this.isShowHistory = !this.isShowHistory
  }

  public handleClick(action: string) {
    switch (action) {
      case 'packUp':
        this.packUp()
        break
      case 'comprehensiveSearch':
        this.comprehensiveSearch()
        break
      case 'resetForm':
        this.resetForm()
        break
      case 'onExport':
        this.exportLayerModalVisible = true
        break
      default:
        break
    }
  }

  /**
   * 收起图层数据详情
   */
  public packUp() {
    if (this.fullScreenState) {
      this.fullScreen(true)
    } else {
      this.$emit('pack-up')
    }
  }

  /**
   * 综合搜索
   */
  public comprehensiveSearch() {
    this.$message.warn('暂不支持！')
  }

  /**
   * 重置
   */
  public resetForm() {
    this.$message.warn('暂不支持！')
  }

  /**
   * 下载导出
   */
  public confirmLayerExport() {
    if (this.columnCount === 0) {
      this.$message.warning('当前表暂无数据，无法导出')
      return
    }
    this.exportLayerModalVisible = false
    this.$message.warn('暂不支持！')
    // window.open(`${baseURL}/task/download?taskId=${this.selectNode.id}`)
  }

  /**
   * 全屏
   */
  public fullScreen(packUp: boolean) {
    this.$emit('gis-data-full', packUp)
  }

  /**
   * 切换历史记录
   * @private
   */
  private onChangeHistory() {
    if (
      this.$refs.dataColumns &&
      typeof (this.$refs.dataColumns as any).scrollLeft === 'function'
    ) {
      ;(this.$refs.dataColumns as any).scrollLeft(0)
    }
  }
}
</script>

<style lang="less" scoped>
.gis-edit-panel-container {
  background: #f0f2f5;
  display: flex;
  height: 100%;
  position: relative;

  .loading {
    align-items: center;
    background-color: rgba(255, 255, 255, 0.6);
    bottom: 0;
    display: flex;
    justify-content: center;
    left: 0;
    position: absolute;
    right: 0;
    top: 38px;
    z-index: 999;
  }

  .left-super-container {
    flex: 1;
    flex-direction: column;
    height: 100%;
    min-width: 0;
    overflow-y: hidden;

    .gis-data-header {
      align-items: center;
      background: #eff0f7;
      display: flex;
      height: 38px;
      justify-content: space-between;
      line-height: 38px;
      padding: 0 16px;
      position: relative;
      user-select: none;

      .left-header {
        align-items: center;
        display: flex;

        .visible-state {
          margin-left: 6px;
        }

        .count-info {
          color: #222432;
          font-size: 12px;
          letter-spacing: 1.12px;
          margin-left: 8px;
          opacity: 0.5;
        }

        // 历史操作
        .history-toggle-icon {
          color: #5d637e;
          cursor: pointer;
          display: flex;
          font-size: 16px;
          margin-left: 12px;
          padding: 4px;

          &.active,
          &:hover {
            background-color: rgba(105, 115, 255, 0.1);
            color: #6973ff;
          }
        }
      }

      .right-header {
        display: flex;

        .tool-btn {
          align-items: center;
          border-radius: 2px;
          color: rgb(93, 99, 126);
          cursor: pointer;
          display: flex;
          font-size: 16px;
          margin: 0 5px;
          padding: 4px;
          position: relative;
          user-select: none;

          &:hover {
            background-color: rgba(105, 115, 255, 0.1);
            color: #6973ff;
          }
        }

        .disabled-btn {
          cursor: not-allowed !important;
        }
      }
    }

    .left-main {
      display: flex;
      flex: 1;
      height: calc(100% - 38px);

      .middle-container {
        background: #fafafc;
        display: flex;
        flex: 1;
        flex-direction: column;
        height: 100%;
        min-width: 0;
        position: relative;

        // 节点提示信息
        .prompt-information {
          border-left: 1px solid #e9e9e9;
          flex-shrink: 0;
          height: 36px;

          .prompt-information-content {
            align-items: center;
            background: #fff1f0;
            border: 1px solid #ffa39e;
            display: flex;
            height: 32px;
            justify-content: space-between;
            line-height: 32px;
            margin-top: 4px;
            padding: 0 19px;
            width: 100%;

            .prompt-information-text {
              max-width: calc(100% - 24px);
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .close-prompt {
              cursor: pointer;
            }
          }
        }

        .data-columns {
          flex: 0 0 266px;
        }

        .data-table {
          flex: 1;
        }
      }
    }

    .progress-bar {
      animation: gradient 1.5s ease infinite;
      background: linear-gradient(
        90deg,
        #c0bfff78 25%,
        #5760e6 37%,
        #c0bfff78 63%
      );
      background-size: 400% 100%;
      height: 3px;
      width: 100%;
    }
  }

  .right-container {
    background: #fff;
    flex: 0 0 225px;
  }
}

@keyframes gradient {
  0% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}
</style>
